package com.kyzh.core.pager.weal.video


/*import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode*/
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.gushenge.atools.util.AView
import com.gushenge.atools.util.setMargins
import com.gushenge.core.base.fragment.BaseFragment
import com.gushenge.core.beans.Video
import com.gushenge.core.dao.MMKVConsts
import com.gushenge.core.isShangjia
import com.gushenge.core.requests.VideoRequest
import com.gushenge.core.toast
import com.kyzh.core.R
import com.kyzh.core.adapters.BqSoildAdapter
import com.kyzh.core.databinding.FragmentVideoPlayBinding
import com.kyzh.core.dialog.showVideoDiscussDialog
import com.kyzh.core.pager.weal.video.viewmodels.VideoPlayerViewModel
import com.kyzh.core.utils.*
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMWeb
import com.umeng.socialize.shareboard.ShareBoardConfig
import kotlinx.android.synthetic.main.fragment_video_play.*
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.jetbrains.anko.imageView
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.dip
import org.jetbrains.anko.support.v4.runOnUiThread
import org.jetbrains.anko.support.v4.sp
import top.littlefogcat.danmakulib.danmaku.Danmaku
import top.littlefogcat.danmakulib.danmaku.DanmakuManager

/**
 * @author Yun.Lei
 * @email waitshan@163.com
 * @date 2020/1/18
 */
class VideoPlayerFragment : BaseFragment() {


    companion object {
        @JvmStatic
        fun getNewInstance(url: Video): VideoPlayerFragment {
            val fragment = VideoPlayerFragment()
            fragment.arguments = bundleOf("url" to url)
            return fragment
        }
    }

    private val viewModel by viewModels<VideoPlayerViewModel>()
    private var bean = Video()
    private lateinit var binding: FragmentVideoPlayBinding
    private var job: Job? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        bean = arguments?.getSerializable("url") as Video
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_video_play, container, false)
        binding.data = bean
        return binding.root
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.e("onViewCreated: ", bean.image)
        videoPlayer?.apply {
            isNeedShowWifiTip = false
            isLooping = true
            dismissControlTime = 0
            thumbImageView = UI {
                imageView {
                    loadImage(bean.image)
                }
            }.view
            setThumbPlay(true)
        }
        videoPlayer.setUp(bean.url, false, null, null, "")
        initView()
        tvDiscuss.setVisibility(!isShangjia)
    }

    fun startVideo() {
        videoPlayer.startPlayLogic()
    }

    private fun initView() {
        bq.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
        bq.adapter = BqSoildAdapter(R.layout.bq_item, bean.biaoqian)
        tvDetail.setOnClickListener {
            startGameDetailActivity(bean.gid)
        }
        tvZan.onLoginClick(requireActivity()) {
            VideoRequest.videoDianZan(bean.id) {
                val video = bean
                if (bean.is_zan) {
                    video.zan = bean.zan - 1
                } else {
                    video.zan = bean.zan + 1
                }
                video.is_zan = !bean.is_zan
                bean = video
                binding.data = bean
            }
        }
        ivGuanzhu.onLoginClick(requireActivity()) {
            VideoRequest.videoGuanzhu(VideoRequest.VideoAttention.GUANZHU, bean.id) {
                val video = bean
                video.is_guanzhu = !bean.is_guanzhu
                bean = video
                binding.data = bean
            }
        }
        tvDiscuss.setOnClickListener {
            requireContext().showVideoDiscussDialog(bean.id)
        }
        tvShare.setOnClickListener {
            share()
        }

    }

    private fun share() {
        if (requireActivity().showShare()) {
            val config = ShareBoardConfig()
            config.setMenuItemBackgroundShape(ShareBoardConfig.BG_SHAPE_CIRCULAR)
            config.setCancelButtonBackground(Color.rgb(240, 244, 246))
            config.setShareboardBackgroundColor(Color.rgb(240, 244, 246))
            config.setIndicatorVisibility(false)
            config.setTitleText(getString(R.string.share))
            val image = UMImage(context, bean.icon)
            val web = UMWeb(bean.fenxiang)
            web.title = bean.name
            web.setThumb(image)
            web.description = bean.summary
            ShareAction(requireActivity())
                .withMedia(web)
                .setDisplayList(
                    SHARE_MEDIA.WEIXIN,
                    SHARE_MEDIA.WEIXIN_CIRCLE,
                    SHARE_MEDIA.QQ,
                    SHARE_MEDIA.QZONE
                )
                .open(config)
        } else {
            val createQRImage = createQRImage(bean.fenxiang)
            val view = LayoutInflater.from(requireContext()).inflate(R.layout.dialog_share, null)
            val code = view.findViewById<ImageView>(R.id.img_code)
            val save = view.findViewById<TextView>(R.id.tv_save)
            code.setImageBitmap(createQRImage)
            save.setOnClickListener {
                if (createQRImage != null)
                    activity?.saveResource(createQRImage, bean.name) {
                        getString(R.string.saveSuccess).toast()
                    }
            }
            val bottomSheetDialog = BottomSheetDialog(requireContext())
            bottomSheetDialog.setContentView(view)
            bottomSheetDialog.show()
        }

    }

    override fun onResume() {
        super.onResume()
        if (!MMKVConsts.videoHidden) {
            videoPlayer?.startPlayLogic()
        }

        if (MMKVConsts.showDanmuku) {
            ivDanmuku.setImageResource(R.drawable.ic_danmuku_start)
            barrage.visibility = View.VISIBLE
        } else {
            ivDanmuku.setImageResource(R.drawable.ic_danmuku_close)
            barrage.visibility = View.GONE
        }
        ivDanmuku.setMargins(0, AView.getStatusBarHeight(requireActivity()), dip(20), 0)
        ivDanmuku.setOnClickListener {
            MMKVConsts.showDanmuku = !MMKVConsts.showDanmuku
            if (MMKVConsts.showDanmuku) {
                ivDanmuku.setImageResource(R.drawable.ic_danmuku_start)
                barrage.visibility = View.VISIBLE
            } else {
                ivDanmuku.setImageResource(R.drawable.ic_danmuku_close)
                barrage.visibility = View.GONE
            }
        }
        VideoRequest.videoDiscuss(bean.id) {
            val data = this
            val dm = DanmakuManager.getInstance()
            dm.init(requireActivity(), barrage)
            val config: DanmakuManager.Config = dm.config // 弹幕相关设置
            config.durationScroll = 5000// 设置滚动字幕显示时长，默认10秒
            config.maxScrollLine = 12 // 设置滚动字幕最大行数
            config.lineHeight = dip(18) // 设置行高
            job = GlobalScope.launch {
                repeat(20000) {
                    for (i in data) {
                        delay(500)
                        runOnUiThread {
                            val danmaku = Danmaku()
                            danmaku.text = i.content
                            danmaku.size = sp(16)
                            dm.send(danmaku)
                        }
                    }
                }
            }
            job?.start()
        }

    }

    override fun onPause() {
        super.onPause()
        videoPlayer?.onVideoPause()
        job?.cancel()
    }

    override fun onDestroyView() {
        super.onDestroyView()
    }
}
